<template>
  <div class="container">
    <div class="videoContainer" v-if="videoShow">
      <div class="el-icon-close video-icon" @click="videoShow = false"></div>
      <video
        autoplay
        class="videoCss"
        :src="videoSrc"
        controls
        width="700"
        height="350"
      ></video>
    </div>

    <!-- el卡片组件 -->
    <el-card>
      <el-form
        ref="inputLeft"
        :inline="true"
        :model="formInline"
        class="demo-form-inline"
      >
        <!-- 左侧input框 --关键字 -->
        <el-form-item prop="keyword" label="关键字">
          <el-input
            size="small"
            v-model="formInline.keyword"
            placeholder="根据文章标题搜索"
          ></el-input>
        </el-form-item>
        <!-- 中间input框 --状态 -->
        <el-form-item prop="state" label="状态">
          <el-select
            size="small"
            v-model="formInline.state"
            placeholder="请选择"
          >
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <!-- 右侧按钮 -->
        <el-form-item>
          <el-button size="small" plain @click="clear()">清除</el-button>
          <el-button size="small" type="primary" @click="find">搜索</el-button>
        </el-form-item>
        <div style="float: right">
          <el-button
            size="small"
            class="addBtn"
            type="success"
            @click="openDialog('add')"
          >
            <i class="el-icon-edit"></i>
            新增技巧</el-button
          >
        </div>
      </el-form>

      <!-- dialog对话框 新增和修改的对话框---->
      <el-dialog
        @close="closeDialog"
        :title="title"
        :visible="dialogVisible"
        width="50%"
      >
        <el-form
          :model="titleList"
          :rules="rules"
          ref="formdata"
          label-width="100px"
          class="demo-ruleForm"
        >
          <!-- 对话框--文章标题 input -->
          <el-form-item label="文章标题" prop="title">
            <el-input
              v-model="titleList.title"
              placeholder="请输入文章标题"
            ></el-input>
          </el-form-item>
          <!--对话框--文章内容 富文本  -->
          <el-form-item label="文章标题" prop="articleBody" ref="questionForm">
            <!-- 富文本插件 -->
            <quillEditor
              ref="text"
              v-model="titleList.articleBody"
              :options="editorOption"
              @blur="validContent"
            ></quillEditor>
          </el-form-item>

          <!-- 对话框--视频地址 -->
          <el-form-item label="视频地址" prop="videoURL">
            <el-input
              v-model="titleList.videoURL"
              placeholder="请输入视频地址"
            ></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
          <!-- @click="dialogVisible = false" -->
        </span>
      </el-dialog>

      <!-- 预览的对话框 -->
      <el-dialog
        width="65%"
        @close="isShow = false"
        :visible="isShow"
        title="预览文章"
      >
        <h2 class="title">{{ objTitle.title }}</h2>
        <!-- 文章的创建事件、录入人、阅读数11444444 -->
        <div>
          <!-- 录入时间 -->
          <span style="display: inline-block" class="createTime">{{
            objTitle.createTime | formetDate()
          }}</span>
          <!-- <span class="username">{{ objTitle.username }}</span> -->
          <!-- 录入人 -->
          <span
            style="display: inline-block; margin-left: 20px"
            class="username"
          >
            {{ objTitle.username | formetDate() }}
          </span>
          <!-- 浏览图标 -->
          <i
            style="display: inline-block; margin-left: 20px"
            class="el-icon-view"
          ></i>
          <!-- 浏览次数 -->
          <span
            style="display: inline-block; margin-left: 20px"
            class="visits"
            >{{ objTitle.visits }}</span
          >
        </div>
        <div v-html="objTitle.articleBody" class="articleBody"></div>
      </el-dialog>
      <!-- 提示信息 -->
      <el-alert
        :title="`数据一共有${totalCounts}条`"
        type="info"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- el-table组件 文章部分-->
      <el-table :data="tableHead" style="width: 100%">
        <el-table-column type="index" label="序号" width="80">
        </el-table-column>
        <el-table-column prop="title" label="文章标题" width="400">
          <!-- 给文章标题添加 icon图标 -->
          <template slot-scope="scope">
            {{ scope.row.title }}
            <i
              class="el-icon-film"
              v-if="scope.row.hasVideo"
              @click="openVideo(scope.row.videoURL)"
            >
            </i>
          </template>
        </el-table-column>

        <el-table-column prop="visits" label="阅读数" width="100">
        </el-table-column>
        <el-table-column prop="username" label="录入人" width="100">
        </el-table-column>

        <!-- <el-table-column prop="createTime" label="录入时间" width="100">
        </el-table-column> -->

        <el-table-column prop="createTime" label="录入时间" width="160">
          <!-- 处理时间格式---使用管道过滤 -->
          <template #default="{ row }">
            <!-- 使用管道符过滤器 -->
            {{ row.createTime | formetDate() }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            {{ row.state | state }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="{ row }">
            <!-- 预览按钮 -->
            <el-button
              @click.native.prevent="viewRow(row.id)"
              type="text"
              size="small"
            >
              预览
            </el-button>

            <!-- 启用/禁用按钮 -->
            <el-button
              @click.native.prevent="handleStatus(row)"
              type="text"
              size="small"
            >
              {{ row.state === 1 ? "禁用" : "启用" }}
              <!-- <span v-if="row.state === 1">禁用</span>
              <span v-else>启用</span> -->
            </el-button>

            <!-- 编辑按钮 -->
            <el-button
              ref="startEnd"
              :disabled="row.state === 0"
              @click.native.prevent="showData(row.id)"
              type="text"
              size="small"
            >
              修改
            </el-button>
            <!-- 删除按钮 -->
            <el-button
              :disabled="row.state === 0"
              @click.native.prevent="deleteRow(row)"
              type="text"
              size="small"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pagesize"
        background
        layout="->, prev, pager, next,sizes, jumper"
        :total="totalCounts"
      >
      </el-pagination>
      <!-- <el-button @click="openVideo">哈哈</el-button> -->
    </el-card>
  </div>
</template>

<script>
import { list, remove, add, detail, update, changeState } from '@/api/hmmm/articles'
// 富文本编辑器样式
import 'quill/dist/quill.core.css'

import 'quill/dist/quill.snow.css'

import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'

// 富文本编辑器组件
export default {
  name: 'Articles',
  // 挂载富文本编辑器组件
  components: { quillEditor },
  data () {
    const toolbarOptions = [
      ['bold', 'italic', 'underline', 'strike'], // 加粗, 斜体, 不划线, 删除线
      [{ list: 'ordered' }, { list: 'bullet' }],
      ['image', 'upload'] // 链接图片、视频
    ]
    return {
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              upload: function () {
                document.querySelector(' .avatar-uploader input ').click()
              }
            }
          }
          // imageDrop: true, // 拖动加载图片组件。imageResize: {//调整大小组件。
          // imageResize: { // 调整大小组件。
          //   displayStyles: {
          //     backgroundColor: 'black',
          //     border: 'none',
          //     color: 'white'
          //   },
          //   modules: ['Resize', 'Displaysize', 'Toolbar']
          // }
          // keyboard: {
          //   bindings
          // }
        },
        theme: 'snow',
        // 主题
        placeholder: '请输入正文'

      },
      totalCounts: 0, // 总条数
      videoShow: false, // 视频显示与隐藏
      // videoSrc: '', // 视频地址
      flag: '', // 判断弹层的标题是 新增文章还是编辑文章
      row: {}, // 每一行文章
      page: 1, // 页码
      pagesize: 10, // 每页条数
      dialogVisible: false, // 新增和编辑弹层的布尔值
      isShow: false, // 预览对话框的显示与隐藏
      currentPage4: 1,
      // 关键词和状态--页面输入后才有数据
      formInline: {
        keyword: '', // 关键字
        state: ''// 状态
      },
      // 表单数据 每一项的文章数据
      tableHead: [],
      // 预览的需要展示的每一项的文章数据
      objTitle: {},
      // from表单的数据
      titleList: {
        title: '', // 文章标题
        articleBody: '', // 文章内容
        videoURL: '' // 视频路径
      },
      rules: {
        title: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: ['blur', 'change']
          }
        ],
        articleBody: [
          {
            required: true,
            message: '请输入内容',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getList()
  },
  // 计算属性里的方法，可以当成data里的数据使用，写法一样
  computed: {
    // 判断文章当前触发的是新增还是编辑功能，从而给dialog赋值不同的标题
    title () {
      return this.flag === 'add' ? '新增文章' : '编辑文章'
    }
  },
  methods: {
    // 启用-禁用
    async handleStatus (row) {
      if (row.state === 1) {
        row.state = 0
      } else {
        row.state = 1
      }
      await changeState(row)
      this.$message.success('操作成功')
    },
    // 播放视频
    openVideo (url) {
      // console.log('打开视频')
      // console.log(url)
      this.videoSrc = url
      this.videoShow = true
    },
    // 预览
    viewRow (id) {
      this.isShow = true
      const obj = this.tableHead.filter((item) => item.id === id)
      console.log(obj)
      this.objTitle = obj[0]
    },
    // 编辑功能--数据回显
    async showData (rowId) {
      this.openDialog('edit')
      this.titleList.id = rowId
      const { data } = await detail({ id: rowId })
      this.titleList = data
    },
    // 关闭编辑和新增弹层
    closeDialog () {
      this.dialogVisible = false
      this.titleList = {
        title: '',
        articleBody: '',
        videoURL: ''
      }
      this.$refs.formdata.resetFields()
    },
    // 打开编辑和新增弹层
    openDialog (str) {
      this.dialogVisible = true
      this.flag = str
    },
    submit () {
      this.$refs.formdata.validate(async (flag) => {
        if (!flag) return
        if (this.flag === 'add') {
          await add(this.titleList)
          this.$message.success('添加成功')
        } else if (this.flag === 'edit') {
          console.log(this.titleList.id)
          await update(this.titleList)
          this.$message.success('修改成功')
        } else {
        }
        this.page = 1
        this.getList()
        this.closeDialog()
      })
    },

    // 删除功能
    deleteRow (row) {
      /*
        1.弹框提示确认
        2.发送请求（带id，id为row的id--插槽里）
        2.成功提示
        3.重新获取列表，渲染
      */
      this.$confirm('确认删除这条文章？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await remove(row)
          this.$message.success('删除成功')
          this.page--
          if (this.page === 0) return
          this.getList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 获取列表
    async getList () {
      const { data: { items, counts } } = await list({ pagesize: this.pagesize, page: this.page })
      this.totalCounts = counts
      this.tableHead = items
      // console.log(this.tableHead)
      this.tableHead.forEach((item) => {
        if (item.videoURL) {
          // 如果此条文章有视频，就添加一个布尔值的标识，true，然后在图标的标签上动态啊绑定类名，如果为true就显示这个图标
          item.hasVideo = true
        }
      })

      // console.log(res)
    },
    // 搜索
    async find () {
      const { data: { items } } = await list({ pagesize: this.totalCounts, page: 1 }) // 获取所有文章
      if (this.formInline.keyword) {
        const arr = items.filter(item => {
          return item.title.trim() === this.formInline.keyword.trim()
        })
        this.tableHead = arr
      }
      if ([0, 1].includes(this.formInline.state)) {
        console.log(this.formInline.state)
        const arr1 = items.filter(item => {
          return item.state === this.formInline.state
        })
        console.log(arr1)
        this.tableHead = arr1
      }
      if (this.formInline.keyword && [0, 1].includes(this.formInline.state)) {
        const arr = items.filter(item => {
          return (item.title.trim() === this.formInline.keyword.trim()) && (item.state === this.formInline.state)
        })
        this.tableHead = arr
      }
      if (!this.formInline.keyword && ![0, 1].includes(this.formInline.state)) {
        this.tableHead = items
      }
    },
    // 清除 关键字和状态的 input
    clear () {
      console.log('清除')
      this.$refs.inputLeft.resetFields()
    },
    async handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.page = 1
      const {
        data: { items }
      } = await list({ pagesize: this.pagesize })
      console.log(items)
      this.tableHead = items
    },
    async handleCurrentChange (val) {
      this.page = val
      console.log(`当前页: ${val}`)
      const {
        data: { items }
      } = await list({ pagesize: this.pagesize, page: this.page })
      // console.log(items)
      this.tableHead = items
    },
    // 手动校验富文本
    validContent () {
      if (this.$refs.text.value.trim() === '') {
        this.$refs.formdata.validateField('articleBody')
      } else {
        this.$refs.questionForm.clearValidate()
      }
    }
  }
}
</script>
<style scoped lang='less'>
// .container{
//   position: relative;
// }
.videoContainer {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: fixed; //固定定位
  left: 70vh;
  top: 10vh;
  z-index: 999;
}
.articleBody {
  background-color: #f5f5f5;
  margin-top: 10px;
  padding: 10px;
  border-top: dashed 1px rgb(161, 159, 159);
}

.videoCss {
  margin-top: 20px;
}

::v-deep {
  // .articleBody{
  //   p{
  //     img{
  //       width: 720px;
  //     }
  //   }
  // }
  // .ql-align-center {
  //   img {
  //     width: 720px;
  //   }
  // }
  //富文本内容高度
  .ql-container {
    min-height: 150px;
  }
  .video-icon {
    width: 10vh;
    height: 10vh;
    font-size: 3vh;
    text-align: center;
    line-height: 10vh;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.3);
    border-radius: 50%;
  }
  .el-card {
    margin: 20px;
  }
  // .quillEditorr {
  //   min-height: 500px;
  //   // height: 200px;
  // }
  .el-icon-film {
    color: blue;
  }
  .addBtn {
    margin-right: 0px;
  }
}
</style>
